<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/4/17
 * Time: 14:51
 * @copyright: ©2024 永州微聚 商网络科技有限公司
 * @link: https://www.weijuYunke.com
 */
namespace app\admin\controller;
use app\Request;
use PDO;

class Install{

    public function index(Request $request)
    {
       
        $sql_url = APP_PATH.'/install/dazi.sql';
        $param = $request->param();
        $db_host =  trim($param['db_host']);
        $db_port = trim($param['db_port']);
        $db_user = trim($param['db_user']);
        $db_pwd = trim($param['db_pwd']);
        $db_name = trim($param['db_name']);
        $db_prefix = trim($param['db_prefix']);
        $admin = trim($param['admin']);
        $password = trim($param['password']);
        $rpassword = trim($param['rpassword']);
        if (!$db_host || !$db_port || !$db_user || !$db_pwd || !$db_name || !$db_prefix || !$admin || !$password) {
            return error('输入不完整，请检查');
        }
        if (strpos($db_prefix, '.') !== false) {
            return error('数据表前缀为空，或者格式错误，请检查');

        }

        if (strlen($admin) > 15 || preg_match("/^$|^c:\\con\\con$|　|[,\"\s\t\<\>&]|^游客|^Guest/is", $admin)) {
            //$install_error .= '非法用户名，用户名长度不应当超过 15 个英文字符，且不能包含特殊字符，一般是中文，字母或者数字';
        }

       /* if (!preg_match("/^\w{3,12}$/", $admin)) {
            $install_error .= "用户名只能由3-12位数字、字母、下划线组合";
        }*/
        if (!preg_match("/^[\S]{6,16}$/", $password)) {
            return error('密码长度必须在6-16位之间，不能包含空格');

        }
        if ($password !== $rpassword) {
            return error('两次输入的密码不一致');
        }
        //检测能否读取安装文件
        $sql = file_get_contents($sql_url);
        if (!$sql) {
            return error('数据库文件无法打开');

        }
        $sql = str_replace("`dz_", "`{$db_prefix}", $sql);


        try {
            $pdo = new PDO("mysql:host={$db_host};port={$db_port}", $db_user, $db_pwd, array(
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,

            ));
        } catch (\Exception $e) {
            return error($e->getMessage());
            return error('数据库连接失败');
        }
        //检测是否支持innodb存储引擎
        $pdoStatement = $pdo->query("SHOW VARIABLES LIKE 'innodb_version'");
        $result = $pdoStatement->fetch();
        if (!$result) {
            return error('当前数据库不支持innodb存储引擎，请开启后再重新尝试安装');
        }
        $pdo->query("CREATE DATABASE IF NOT EXISTS `{$db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;");
        $pdo->query("USE `{$db_name}`");
        $this->runquery($sql, $db_prefix, $pdo);

        $sitepath = strtolower(substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/')));
        $sitepath = str_replace('install', "", $sitepath);
      //  $auto_site_url = strtolower('http://' . $_SERVER['HTTP_HOST'] . $sitepath);
        $this->write_config($db_host,$db_port,$db_user,$db_pwd,$db_name,$db_prefix);

        $salt = createNonceStr(4);
        $password  = md5(md5($password) . $salt);
        $pdo->query("UPDATE {$db_prefix}staff_account SET name = '{$admin}',password = '{$password}', salt = '{$salt}' WHERE name = 'admin'");
        fopen(APP_PATH.'/install/install.lock', 'w');
        return success('安装成功');
    }

    public function runquery($sql, $db_prefix, $pdo)
    {

        if (!isset($sql) || empty($sql)) {
            return;
        }
        $sql = str_replace("\r", "\n", str_replace('#__', $db_prefix, $sql));
        $ret = array();
        $num = 0;
        foreach (explode(";\n", trim($sql)) as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            foreach ($queries as $query) {
                $ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0] . $query[1] == '--') ? '' : $query;
            }
            $num++;
        }
        unset($sql);
        foreach ($ret as $query) {
            $query = trim($query);
            if ($query) {
                if (substr($query, 0, 12) == 'CREATE TABLE') {
                    $line = explode('`', $query);
                    $data_name = $line[1];
                    $pdo->exec($query);
                    unset($line, $data_name);
                } else {
                    $pdo->exec($query);
                }
            }
        }
    }


//写入config文件
    function write_config($db_host,$db_port,$db_user,$db_pwd,$db_name,$db_prefix)
    {
            $charset = 'utf8mb4';


    $_env =
"APP_DEBUG = false
[APP]
DEFAULT_TIMEZONE = Asia/Shanghai

[DATABASE]
TYPE = mysql
HOSTNAME = {$db_host}
DATABASE = {$db_name}
PREFIX = {$db_prefix}
USERNAME = {$db_user}
PASSWORD = {$db_pwd}
HOSTPORT = {$db_port}
CHARSET = {$charset}
DEBUG = false

[LANG]
default_lang = zh-cn";
file_put_contents(APP_PATH.'/../.env', $_env);

}


    public function isInstall(){
        $file = APP_PATH.'/install/install.lock';
        if (file_exists($file)) {
            return success('无需安装');
        } else {
            return error('请安装');
        }
    }




}
